package com.zking.forward.shopping;

import com.zking.dao.OrderDao;
import com.zking.dao.OrderDetailDao;
import com.zking.dao.ProductDao;
import com.zking.dao.ShopCarDao;
import com.zking.entity.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/balance")
public class Balance extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("Balance===进来");

        //一、生成一个订单数据
        //1.得到当前登录的用户的信息
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String eu_user_id = user.getEu_user_id();
        //2.计算出这个订单的金额
        final List<ShopCar> slist = ShopCarDao.selectShopCarById(user.getEu_user_id());
        //实际上购物车列表页面显示的数据List<Product>
        List<Product> list = new ArrayList<Product>();
        double eo_cost= 0;//订单的总价格
        for (ShopCar shopCar : slist) {//循环购物车中当前用户购买的商品的信息
            Integer ep_id = shopCar.getEp_id();//商品的编号
            Integer count = shopCar.getCount();//商品的数量
            Product product = ProductDao.selectProductById(ep_id);//根据商品编号得到对应的商品对象
            if(product==null){
                continue;
            }
            product.setCount(count);//根据购物车中购买的数量更新当前商品的数量
            list.add(product);
            eo_cost += count*product.getEp_price();
        }
        //一、根据购物车列表的数据生成一条订单表数据--返回最新的订单号
        Order order = new Order(user.getEu_user_id(), user.getEu_user_name(), user.getEu_address(), eo_cost, 1, 1);
        int eo_id = OrderDao.addOrder(order);
        System.out.println("订单号=="+eo_id);

        //二、生成对应的订单详情
        for (Product p : list) {
            OrderDetail detail = new OrderDetail(eo_id,p.getEp_id(),p.getCount(),p.getEp_price()*p.getCount());
            //添加订单详细
            OrderDetailDao.addOrderDetail(detail);
            //更新商品的库存
            ProductDao.updateStock(p.getEp_id(),p.getCount());
            //从购物车中该用户购买的该商品删掉
            ShopCarDao.deleteShopCar(eu_user_id,p.getEp_id());
        }
        response.sendRedirect("shopping-result.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
